//
//  ConnectModel.m
//  UI-20网络Block
//
//  Created by Xue Senhong on 15/5/15.
//  Copyright (c) 2015年 薛森鸿. All rights reserved.
//

#import "ConnectModel.h"

@interface ConnectModel ()<NSURLConnectionDataDelegate>

@end

@implementation ConnectModel

+ (void)connctUrl:(NSString *)url block:(void(^)(NSData *data))block
{
    ConnectModel *model = [[ConnectModel alloc] init];
    model.finishBlock = block;
    [model startConnect:url];
    [model release];
}

+ (void)connctUrl:(NSString *)url andPost:(NSString *)post block:(void(^)(NSData *data))block
{
    ConnectModel *model = [[ConnectModel alloc] init];
    model.finishBlock = block;
    [model startPostConnect:url postUrl:post];
    [model release];
}

- (void)startConnect:(NSString *)str
{
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)startPostConnect:(NSString *)str postUrl:(NSString *)post
{
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    
    NSString *par = post;
    NSData *data = [par dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection connectionWithRequest:request delegate:self];


}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.recieveData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.recieveData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.finishBlock(self.recieveData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"%@", error);
}
@end
